"use client"

import { useState, useEffect } from 'react'

interface Course {
  lesson_number: string
  course_name: string
  target_char: string
}

interface GamePracticeProps {
  currentCourse?: Course
}

interface Question {
  id: number
  type: 'choice' | 'match' | 'fill'
  question: string
  options: string[]
  correct: number
  explanation: string
  points: number
  difficulty: 'easy' | 'medium' | 'hard'
}

interface GameState {
  currentLevel: number
  score: number
  lives: number
  streak: number
  totalQuestions: number
  correctAnswers: number
}

export function GamePractice({ currentCourse }: GamePracticeProps) {
  const [gameState, setGameState] = useState<GameState>({
    currentLevel: 1,
    score: 0,
    lives: 3,
    streak: 0,
    totalQuestions: 0,
    correctAnswers: 0
  })
  
  const [currentQuestion, setCurrentQuestion] = useState<Question | null>(null)
  const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null)
  const [showResult, setShowResult] = useState(false)
  const [isCorrect, setIsCorrect] = useState(false)
  const [gameStarted, setGameStarted] = useState(false)
  const [showCelebration, setShowCelebration] = useState(false)

  // 根据当前汉字生成题目
  const generateQuestions = (char: string): Question[] => {
    const questionBank: { [key: string]: Question[] } = {
      '木': [
        {
          id: 1,
          type: 'choice',
          question: '"木"字的基本含义是什么？',
          options: ['石头', '树木', '水流', '火焰'],
          correct: 1,
          explanation: '木字代表树木、植物，是汉字中的基本部首之一。',
          points: 10,
          difficulty: 'easy'
        },
        {
          id: 2,
          type: 'choice',
          question: '下面哪个字包含"木"字旁？',
          options: ['林', '水', '火', '土'],
          correct: 0,
          explanation: '"林"字由两个"木"字组成，表示树木成林的意思。',
          points: 15,
          difficulty: 'medium'
        },
        {
          id: 3,
          type: 'choice',
          question: '"木工"这个词中的"木"指的是什么？',
          options: ['木材', '树叶', '树根', '木炭'],
          correct: 0,
          explanation: '木工是制作木器的工匠，这里的"木"指木材、木料。',
          points: 20,
          difficulty: 'hard'
        },
        {
          id: 4,
          type: 'choice',
          question: '在五行中，"木"代表什么特性？',
          options: ['生长', '流动', '燃烧', '坚硬'],
          correct: 0,
          explanation: '在五行理论中，木代表生长、生机、向上的力量。',
          points: 25,
          difficulty: 'hard'
        }
      ],
      '水': [
        {
          id: 1,
          type: 'choice',
          question: '"水"的基本特性是什么？',
          options: ['固体', '液体', '气体', '等离子'],
          correct: 1,
          explanation: '水在常温下是无色无味的液体，是生命之源。',
          points: 10,
          difficulty: 'easy'
        },
        {
          id: 2,
          type: 'choice',
          question: '下面哪个成语与"水"有关？',
          options: ['火上浇油', '水滴石穿', '木已成舟', '土崩瓦解'],
          correct: 1,
          explanation: '"水滴石穿"比喻坚持不懈，积少成多的力量。',
          points: 15,
          difficulty: 'medium'
        }
      ]
    }

    return questionBank[char] || []
  }

  // 开始游戏
  const startGame = () => {
    const questions = generateQuestions(currentCourse?.target_char || '木')
    if (questions.length > 0) {
      setCurrentQuestion(questions[0])
      setGameStarted(true)
      setGameState(prev => ({ ...prev, totalQuestions: questions.length }))
    }
  }

  // 选择答案
  const selectAnswer = (answerIndex: number) => {
    if (showResult) return
    setSelectedAnswer(answerIndex)
  }

  // 提交答案
  const submitAnswer = () => {
    if (selectedAnswer === null || !currentQuestion) return

    const correct = selectedAnswer === currentQuestion.correct
    setIsCorrect(correct)
    setShowResult(true)

    // 更新游戏状态
    setGameState(prev => {
      const newState = {
        ...prev,
        totalQuestions: prev.totalQuestions,
        correctAnswers: correct ? prev.correctAnswers + 1 : prev.correctAnswers,
        score: correct ? prev.score + currentQuestion.points : prev.score,
        streak: correct ? prev.streak + 1 : 0,
        lives: correct ? prev.lives : Math.max(0, prev.lives - 1)
      }

      // 连击奖励
      if (correct && newState.streak >= 3) {
        newState.score += 50 // 连击奖励
      }

      return newState
    })

    // 正确答案的庆祝动画
    if (correct) {
      setShowCelebration(true)
      setTimeout(() => setShowCelebration(false), 2000)
    }
  }

  // 下一题
  const nextQuestion = () => {
    const questions = generateQuestions(currentCourse?.target_char || '木')
    const currentIndex = questions.findIndex(q => q.id === currentQuestion?.id)
    
    if (currentIndex < questions.length - 1) {
      setCurrentQuestion(questions[currentIndex + 1])
      setSelectedAnswer(null)
      setShowResult(false)
      setGameState(prev => ({ ...prev, currentLevel: prev.currentLevel + 1 }))
    } else {
      // 游戏结束
      setGameStarted(false)
      setCurrentQuestion(null)
    }
  }

  // 重新开始
  const restartGame = () => {
    setGameState({
      currentLevel: 1,
      score: 0,
      lives: 3,
      streak: 0,
      totalQuestions: 0,
      correctAnswers: 0
    })
    setCurrentQuestion(null)
    setSelectedAnswer(null)
    setShowResult(false)
    setGameStarted(false)
  }

  // 获取难度颜色
  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty) {
      case 'easy': return 'from-green-400 to-green-500'
      case 'medium': return 'from-yellow-400 to-orange-500'
      case 'hard': return 'from-red-400 to-red-500'
      default: return 'from-gray-400 to-gray-500'
    }
  }

  // 获取难度标签
  const getDifficultyLabel = (difficulty: string) => {
    switch (difficulty) {
      case 'easy': return '简单'
      case 'medium': return '中等'
      case 'hard': return '困难'
      default: return '未知'
    }
  }

  if (!gameStarted) {
    return (
      <div className="h-full flex flex-col bg-gradient-to-br from-purple-50 via-pink-50 to-blue-50">
        {/* 游戏开始界面 */}
        <div className="flex-1 flex items-center justify-center p-6">
          <div className="bg-white/90 backdrop-blur-sm rounded-3xl p-8 shadow-2xl border border-purple-200 max-w-md w-full text-center">
            {/* 游戏图标 */}
            <div className="mb-6">
              <div className="w-20 h-20 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center mx-auto mb-4 animate-bounce">
                <span className="text-3xl">🎮</span>
              </div>
              <h2 className="text-2xl font-bold text-gray-800 mb-2">随堂小练</h2>
              <p className="text-gray-600">"{currentCourse?.target_char || '木'}"字的练习题目</p>
            </div>

            {/* 游戏统计 */}
            {gameState.totalQuestions > 0 && (
              <div className="bg-gradient-to-r from-purple-100 to-pink-100 rounded-xl p-4 mb-6">
                <h3 className="text-lg font-bold text-gray-800 mb-3">上次成绩</h3>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div className="text-center">
                    <div className="text-2xl font-bold text-purple-600">{gameState.score}</div>
                    <div className="text-gray-600">总分</div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-pink-600">
                      {Math.round((gameState.correctAnswers / gameState.totalQuestions) * 100)}%
                    </div>
                    <div className="text-gray-600">正确率</div>
                  </div>
                </div>
              </div>
            )}

            {/* 游戏规则 */}
            <div className="bg-blue-50 rounded-xl p-4 mb-6 text-left">
              <h4 className="font-bold text-blue-800 mb-2">🎯 游戏规则</h4>
              <ul className="text-sm text-blue-700 space-y-1">
                <li>• 回答关于"{currentCourse?.target_char || '木'}"字的问题</li>
                <li>• 答对得分，答错扣生命值</li>
                <li>• 连续答对有额外奖励</li>
                <li>• 挑战所有关卡获得最高分</li>
              </ul>
            </div>

            {/* 开始按钮 */}
            <button
              onClick={startGame}
              className="w-full bg-gradient-to-r from-purple-500 to-pink-500 text-white font-bold py-4 px-6 rounded-xl hover:from-purple-600 hover:to-pink-600 transform hover:scale-105 transition-all duration-300 shadow-lg"
            >
              🚀 开始挑战
            </button>

            {gameState.totalQuestions > 0 && (
              <button
                onClick={restartGame}
                className="w-full mt-3 bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-lg hover:bg-gray-300 transition-colors duration-200"
              >
                重新开始
              </button>
            )}
          </div>
        </div>
      </div>
    )
  }

  if (!currentQuestion) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">🎉</div>
          <h2 className="text-2xl font-bold text-gray-800 mb-4">恭喜完成所有挑战！</h2>
          <div className="bg-gradient-to-r from-yellow-400 to-orange-500 text-white rounded-xl p-6 mb-6">
            <div className="text-3xl font-bold mb-2">{gameState.score} 分</div>
            <div className="text-sm opacity-90">
              正确率: {Math.round((gameState.correctAnswers / gameState.totalQuestions) * 100)}%
            </div>
          </div>
          <button
            onClick={restartGame}
            className="bg-gradient-to-r from-purple-500 to-pink-500 text-white font-bold py-3 px-6 rounded-xl hover:from-purple-600 hover:to-pink-600 transform hover:scale-105 transition-all duration-300"
          >
            再来一次
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col bg-gradient-to-br from-purple-50 via-pink-50 to-blue-50 relative overflow-hidden">
      {/* 庆祝动画 */}
      {showCelebration && (
        <div className="absolute inset-0 z-50 flex items-center justify-center pointer-events-none">
          <div className="text-6xl animate-bounce">🎉</div>
          <div className="absolute inset-0 bg-yellow-300/20 animate-pulse rounded-full"></div>
        </div>
      )}

      {/* 顶部状态栏 */}
      <div className="bg-white/80 backdrop-blur-sm p-4 border-b border-purple-200">
        <div className="flex items-center justify-between">
          {/* 左侧：关卡和生命值 */}
          <div className="flex items-center space-x-4">
            <div className="bg-gradient-to-r from-purple-500 to-pink-500 text-white px-3 py-1 rounded-full text-sm font-bold">
              第 {gameState.currentLevel} 关
            </div>
            <div className="flex items-center space-x-1">
              {[...Array(3)].map((_, i) => (
                <span key={i} className={`text-lg ${i < gameState.lives ? 'text-red-500' : 'text-gray-300'}`}>
                  ❤️
                </span>
              ))}
            </div>
          </div>

          {/* 右侧：分数和连击 */}
          <div className="flex items-center space-x-4">
            {gameState.streak > 0 && (
              <div className="bg-gradient-to-r from-yellow-400 to-orange-500 text-white px-3 py-1 rounded-full text-sm font-bold animate-pulse">
                🔥 {gameState.streak} 连击
              </div>
            )}
            <div className="bg-gradient-to-r from-blue-500 to-indigo-500 text-white px-3 py-1 rounded-full text-sm font-bold">
              💎 {gameState.score} 分
            </div>
          </div>
        </div>
      </div>

      {/* 主要内容区域 */}
      <div className="flex-1 p-6 flex items-center justify-center">
        <div className="max-w-2xl w-full">
          {/* 题目卡片 */}
          <div className="bg-white/95 backdrop-blur-sm rounded-3xl p-8 shadow-2xl border border-purple-200 mb-6 transform hover:scale-105 transition-all duration-300">
            {/* 难度标签 */}
            <div className="flex items-center justify-between mb-6">
              <div className={`bg-gradient-to-r ${getDifficultyColor(currentQuestion.difficulty)} text-white px-3 py-1 rounded-full text-sm font-bold`}>
                {getDifficultyLabel(currentQuestion.difficulty)}
              </div>
              <div className="text-sm text-gray-500">
                +{currentQuestion.points} 分
              </div>
            </div>

            {/* 题目 */}
            <h3 className="text-xl font-bold text-gray-800 mb-6 leading-relaxed">
              {currentQuestion.question}
            </h3>

            {/* 选项 */}
            <div className="grid grid-cols-1 gap-3 mb-6">
              {currentQuestion.options.map((option, index) => (
                <button
                  key={index}
                  onClick={() => selectAnswer(index)}
                  disabled={showResult}
                  className={`
                    p-4 rounded-xl text-left font-medium transition-all duration-300 transform hover:scale-105
                    ${selectedAnswer === index
                      ? showResult
                        ? isCorrect && selectedAnswer === currentQuestion.correct
                          ? 'bg-gradient-to-r from-green-400 to-green-500 text-white shadow-lg'
                          : selectedAnswer === currentQuestion.correct
                            ? 'bg-gradient-to-r from-green-400 to-green-500 text-white shadow-lg'
                            : 'bg-gradient-to-r from-red-400 to-red-500 text-white shadow-lg'
                        : 'bg-gradient-to-r from-purple-500 to-pink-500 text-white shadow-lg'
                      : showResult && index === currentQuestion.correct
                        ? 'bg-gradient-to-r from-green-400 to-green-500 text-white shadow-lg'
                        : 'bg-gray-100 hover:bg-gray-200 text-gray-800 border-2 border-transparent hover:border-purple-300'
                    }
                    ${showResult ? 'cursor-not-allowed' : 'cursor-pointer'}
                  `}
                >
                  <div className="flex items-center space-x-3">
                    <div className={`
                      w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold
                      ${selectedAnswer === index || (showResult && index === currentQuestion.correct)
                        ? 'bg-white/20 text-white'
                        : 'bg-purple-100 text-purple-600'
                      }
                    `}>
                      {String.fromCharCode(65 + index)}
                    </div>
                    <span>{option}</span>
                  </div>
                </button>
              ))}
            </div>

            {/* 解释 */}
            {showResult && (
              <div className="bg-blue-50 rounded-xl p-4 mb-4 border-l-4 border-blue-400">
                <div className="flex items-start space-x-2">
                  <span className="text-blue-500 text-lg">💡</span>
                  <div>
                    <div className="font-medium text-blue-800 mb-1">解释</div>
                    <div className="text-blue-700 text-sm">{currentQuestion.explanation}</div>
                  </div>
                </div>
              </div>
            )}

            {/* 按钮区域 */}
            <div className="flex justify-center">
              {!showResult ? (
                <button
                  onClick={submitAnswer}
                  disabled={selectedAnswer === null}
                  className={`
                    px-8 py-3 rounded-xl font-bold transition-all duration-300 transform hover:scale-105
                    ${selectedAnswer !== null
                      ? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white shadow-lg hover:from-purple-600 hover:to-pink-600'
                      : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                    }
                  `}
                >
                  确认答案
                </button>
              ) : (
                <button
                  onClick={nextQuestion}
                  className="bg-gradient-to-r from-green-500 to-blue-500 text-white font-bold px-8 py-3 rounded-xl hover:from-green-600 hover:to-blue-600 transform hover:scale-105 transition-all duration-300 shadow-lg"
                >
                  下一题 →
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
} 